<template>
  <view>
    <!-- 搜索款 -->
    <view class="search-box">
      <uni-search-bar @confirm="search" @input="input" :radius="100" cancelButton="none"></uni-search-bar>
    </view>
    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="kw.trim()!==''">
      <view class="sugg-item" v-for="(item ,i) in searchList" :key="i" @click="jumpDetail(item.goods_id,item.goods_name)">
        <view class="goods-name">{{item.goods_name}}</view>
        <uni-icons type="arrowright" size="16" v-if="item.goods_name!=='暂无此商品！'"></uni-icons>
      </view>
    </view>
    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" @click="clearHistory"></uni-icons>
      </view>
      <view class="history-list">
        <uni-tag :text="item" v-for="(item,i) in searchHistory" :key="i" @click="jumpGoodsList(item)"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        // 搜索关键字
        kw: '',
        // 防抖延时器
        timer: null,
        // 搜索结果列表
        searchList: [],
        // 搜索历史
        searchHistory: [],
      };
    },
    onLoad() {
      this.searchHistory = JSON.parse(uni.getStorageSync('kw') || '[]')
    },
    methods: {
      input(e) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.kw = e.value
          console.log(this.kw)
          this.getSearchList()
        }, 500)
      },
      // 获取商品列表
      async getSearchList() {
        if (this.kw.trim() === '') {
          this.searchList = []
          return
        }
        // 搜索建议列表
        const {
          data: res
        } = await uni.$http.get('/goods/search', {
          query: this.kw.trim()
        })
        if (res.meta.status !== 200) return uni.$showMsg()
        this.searchList = res.message.goods
        if (this.searchList.length === 0) {
          this.searchList.push({
            goods_name: '暂无此商品！'
          })
        }
        // console.log(this.searchList)
        // 历史记录
        let index = this.searchHistory.indexOf(this.kw.trim())
        if (index === -1) {
          this.searchHistory.unshift(this.kw)
        } else {
          this.searchHistory.splice(index, 1)
          this.searchHistory.unshift(this.kw)
        }
        uni.setStorageSync('kw', JSON.stringify(this.searchHistory))
        // console.log(this.searchHistory)
      },
      // 跳转详情
      jumpDetail(id, name) {
        if (name !== '暂无此商品！') {
          uni.navigateTo({
            url: '/subpkg/goods_detail/goods_detail?goods_id=' + id
          })
        }
      },
      // 跳转商品列表
      jumpGoodsList(kw) {
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + kw
        })
      },
      // 清空搜索历史
      clearHistory() {
        this.searchHistory = []
        uni.setStorageSync('kw', '[]')
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    // 设置定位效果为“吸顶”,
    // fixed会影响盒子大小，粘性定位 sticky则不会
    position: sticky;
    // 吸顶的“位置”
    top: 0;
    // 提高层级，防止被轮播图覆盖
    z-index: 999;
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .goods-name {
        // 文字不允许换行（单行文本）
        white-space: nowrap;
        // 溢出部分隐藏
        overflow: hidden;
        // 文本溢出后，使用 ... 代替
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }
  }

  .history-box {
    padding: 0 5px;

    .history-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 40px;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;

      .uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }
    }
  }
</style>
